package com.foucus.myfouces.MVP.View.views.Activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.foucus.myfouces.Api.GankService;
import com.foucus.myfouces.Base.BaseActivity;
import com.foucus.myfouces.Base.BaseReq;
import com.foucus.myfouces.Base.Setting;
import com.foucus.myfouces.MVP.Model.VideoDetailResp;
import com.foucus.myfouces.R;
import com.foucus.myfouces.Resource.HttpUtil.ServiceFactory;
import com.foucus.myfouces.Resource.Util.CommonUtil;
import com.foucus.myfouces.Resource.Util.GliderUtil;
import com.foucus.myfouces.Resource.Util.GsonImpl;
import com.foucus.myfouces.Resource.Util.JsonUtil;
import com.foucus.myfouces.Resource.Util.MediaController;
import com.foucus.myfouces.Resource.view.CircleImageView;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.widget.PLVideoTextureView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yf-06 on 2017/7/2.
 */

public class VideoDetail extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.img_back)
    ImageView img_back;
    @Bind(R.id.lly_back)
    LinearLayout lly_back;
    @Bind(R.id.tv_title_bar_title)
    TextView tv_title_bar_title;
    @Bind(R.id.img_title_bar_right)
    ImageView img_title_bar_right;
    @Bind(R.id.lly_title_bar_right)
    LinearLayout lly_title_bar_right;
    @Bind(R.id.tv_save)
    TextView tv_save;
    @Bind(R.id.VideoView)
    PLVideoTextureView mVideoView;
    @Bind(R.id.img_video_loader)
    ImageView img_video_loader;
    @Bind(R.id.lly_loading)
    LinearLayout lly_loading;
    @Bind(R.id.imgbtn_play)
    ImageButton imgbtn_play;
    @Bind(R.id.fly_video)
    FrameLayout fly_video;
    @Bind(R.id.rly_media)
    RelativeLayout rly_media;
    @Bind(R.id.rly_title)
    RelativeLayout rly_title;
    @Bind(R.id.pcfl_videodetail)
    PtrClassicFrameLayout pcfl_videodetail;
    @Bind(R.id.cimg_vd_head)
    CircleImageView cimg_vd_head;
    @Bind(R.id.tv_vd_name)
    TextView tv_vd_name;
    @Bind(R.id.tv_vd_time)
    TextView tv_vd_time;
    @Bind(R.id.img_vd_attention)
    ImageView img_vd_attention;
    @Bind(R.id.rly_vd_title)
    RelativeLayout rly_vd_title;


    private Activity mActivity;
    private String videoId, videoUrl;
    private String mVideoPath = null;

    private MediaController mMediaController;
    private int MESSAGE_ID_RECONNECTING = 0x01;
    private boolean mIsActivityPaused = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_detail);
        ButterKnife.bind(this);
        mActivity = this;
        init();
        initVideo();
        initLayout();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsActivityPaused = false;
        mVideoView.start();
    }

    private void init() {
        videoId = getIntent().getExtras().getString("videoId");
        getVideoDetail(videoId);
        Log.e("ssss", "videoUrl==>" + videoId);

        lly_back.setVisibility(View.VISIBLE);
        tv_title_bar_title.setText("作品详情");
        img_title_bar_right.setImageDrawable(getResources().getDrawable(R.mipmap.icon_other));
        lly_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        pcfl_videodetail.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pcfl_videodetail.refreshComplete();
//                getBannerAd();
            }
        });
    }

    private void initVideo() {
        AVOptions options = new AVOptions();
        // the unit of timeout is ms
        options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 10 * 1000);
        options.setInteger(AVOptions.KEY_GET_AV_FRAME_TIMEOUT, 10 * 1000);
        options.setInteger(AVOptions.KEY_PROBESIZE, 128 * 1024);
        options.setInteger(AVOptions.KEY_LIVE_STREAMING, 0);
//        options.setInteger(AVOptions.KEY_DELAY_OPTIMIZATION, 1);
        options.setInteger(AVOptions.KEY_MEDIACODEC, 2);
        options.setInteger(AVOptions.KEY_START_ON_PREPARED, 0);

        mVideoView.setAVOptions(options);
        mVideoView.setBufferingIndicator(lly_loading);
        mMediaController = new MediaController(this, true, fly_video);
        mVideoView.setMediaController(mMediaController);
        mVideoView.setOnCompletionListener(mOnCompletionListener);
        mVideoView.setOnErrorListener(mOnErrorListener);

        //播放视频
        imgbtn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPlay("");
            }
        });
    }

    @OnClick({R.id.lly_title_bar_right})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lly_title_bar_right:
                Log.e("ssss", "更多");
                break;
        }

    }

    /**
     * 播放影片
     *
     * @param video_url
     */
    public void onPlay(String video_url) {

        mVideoPath = video_url;

        if (!CommonUtil.isNetworkAvailable(getApplicationContext())) {
            showToastTips("当前网络不存在");
            return;
        }

        if (!CommonUtil.isNetworkWifi(getApplicationContext())) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setMessage("确定要继续播放");
            builder.setTitle("您当前的网络不是WIFI状态");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //在调用播放器的控制接口之前，必须先设置好播放地址。传入播放地址，可以是 /path/to/local.mp4 本地文件绝对路径，或 HLS URL，或 RTMP URL
                    mVideoView.setVideoPath(mVideoPath);
                    mVideoView.start();
                    imgbtn_play.setVisibility(View.GONE);
                    img_video_loader.setVisibility(View.GONE);
                    lly_loading.setVisibility(View.VISIBLE);
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
            return;
        }

        mVideoView.setVideoPath(mVideoPath);
        mVideoView.start();
        imgbtn_play.setVisibility(View.GONE);
        img_video_loader.setVisibility(View.GONE);
        lly_loading.setVisibility(View.VISIBLE);
    }


    /**
     * 获取影片详情
     *
     * @param id
     */
    private void getVideoDetail(final String id) {
        BaseReq req = new BaseReq();
        req.setValue("member", "");
        req.setValue("video", id);
        ServiceFactory
                .getInstance()
                .createService(GankService.class)
                .getVideoDetail(req.getSecret("获取影片详情"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        String response = JsonUtil.JsonToStr(responseBody);
                        boolean isflag = Setting.isRight(mActivity, response);
                        if (isflag) {
                            VideoDetailResp resp = GsonImpl.get().toObject(response.toString(), VideoDetailResp.class);
                            videoUrl = resp.getResult().getData().getUrl();
                            GliderUtil.bannerGlider(mActivity, resp.getResult().getData().getCreated_by().getThumb(), cimg_vd_head);
                            tv_vd_name.setText(resp.getResult().getData().getName());
                            tv_vd_time.setText(resp.getResult().getData().getCreated_at());

                            onPlay(videoUrl);
                        }
                    }
                });
    }

    /**
     * @param newConfig 在配置改变
     *                  <p>
     *                  ORIENTATION_PORTRAIT 竖屏；
     *                  ORIENTATION_LANDSCAPE 横屏
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {//竖屏
            Log.e("ssss", "1111111111");
            rly_media.setLayoutParams(new FrameLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT));
            rly_title.setVisibility(View.VISIBLE);
            rly_vd_title.setVisibility(View.VISIBLE);
            initLayout();

            pcfl_videodetail.setPtrHandler(new PtrDefaultHandler() {
                @Override
                public void onRefreshBegin(PtrFrameLayout frame) {
                    pcfl_videodetail.refreshComplete();
//                getBannerAd();
                }
            });
        } else {
            Log.e("ssss", "2222222222");
            WindowManager wm = (WindowManager) this
                    .getSystemService(Context.WINDOW_SERVICE);
            Rect frame = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            int statusBarHeight = frame.top;  //状态栏高
            int width = wm.getDefaultDisplay().getWidth();
            int height = wm.getDefaultDisplay().getHeight() - statusBarHeight;
//            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, wm.getDefaultDisplay().getHeight());
            rly_media.setLayoutParams(layoutParams);
//            disableScroll();
            rly_title.setVisibility(View.GONE);
            rly_vd_title.setVisibility(View.GONE);
            pcfl_videodetail.setPtrHandler(null);
        }
        super.onConfigurationChanged(newConfig);
    }

    private PLMediaPlayer.OnCompletionListener mOnCompletionListener = new PLMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(PLMediaPlayer plMediaPlayer) {
            mVideoView.pause();
            mVideoView.stopPlayback();
            mMediaController.stopPlayback();
            mMediaController.setEnabled(false);
            imgbtn_play.setVisibility(View.VISIBLE);
            img_video_loader.setVisibility(View.VISIBLE);
        }
    };
    private PLMediaPlayer.OnErrorListener mOnErrorListener = new PLMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(PLMediaPlayer mp, int errorCode) {
            boolean isNeedReconnect = false;
            switch (errorCode) {
                case PLMediaPlayer.ERROR_CODE_INVALID_URI:
                    showToastTips("Invalid URL !");
                    break;
                case PLMediaPlayer.ERROR_CODE_404_NOT_FOUND:
                    showToastTips("404 resource not found !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_REFUSED:
                    showToastTips("Connection refused !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_TIMEOUT:
                    showToastTips("Connection timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_EMPTY_PLAYLIST:
                    showToastTips("Empty playlist !");
                    break;
                case PLMediaPlayer.ERROR_CODE_STREAM_DISCONNECTED:
                    showToastTips("Stream disconnected !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_IO_ERROR:
                    showToastTips("Network IO Error !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_UNAUTHORIZED:
                    showToastTips("Unauthorized Error !");
                    break;
                case PLMediaPlayer.ERROR_CODE_PREPARE_TIMEOUT:
                    showToastTips("Prepare timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.ERROR_CODE_READ_FRAME_TIMEOUT:
                    showToastTips("Read frame timeout !");
                    isNeedReconnect = true;
                    break;
                case PLMediaPlayer.MEDIA_ERROR_UNKNOWN:
                    break;
                default:
                    showToastTips("unknown error !");
                    break;
            }
            // Todo pls handle the error status here, reconnect or call finish()
            if (isNeedReconnect) {
                sendReconnectMessage();
            }
            // Return true means the error has been handled
            // If return false, then `onCompletion` will be called
            return true;
        }
    };

    private void sendReconnectMessage() {
        lly_loading.setVisibility(View.VISIBLE);
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_ID_RECONNECTING), 500);
    }

    protected Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what != MESSAGE_ID_RECONNECTING) {
                return;
            }
            if (mIsActivityPaused || !CommonUtil.isLiveStreamingAvailable()) {
                finish();
                return;
            }
            if (!CommonUtil.isNetworkAvailable(getApplicationContext())) {
                sendReconnectMessage();
                return;
            }
            mVideoView.setVideoPath(mVideoPath);
            mVideoView.start();
        }
    };


    private void showToastTips(final String tips) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CommonUtil.showToast(getApplicationContext(), tips);
            }
        });
    }

    /**
     * 播放影片布局的初始化
     */
    private void initLayout() {
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = width * 360 / 640;

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height);
        rly_media.setLayoutParams(layoutParams);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int mCurrentOrientation = getResources().getConfiguration().orientation;
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
                mMediaController.min();
            } else {
                finish();
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVideoView.pause();
        mVideoView.stopPlayback();
        System.gc();
    }
}
